//
//  HLogin2ViewController.m
//  NursingManages
//
//  Created by HuangZhen on 2017/5/27.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import "HLogin2ViewController.h"
#import "Networking.h"
#import <TMCache.h>
#import "AppDelegate.h"
#import "InitDbTable.h"
#import "AppServiceConfig.h"
#import "HLoginSettingViewController.h"
#import "HAPPUUID.h"
#import <Foundation/Foundation.h>
#import <Security/Security.h>
#import <objc/runtime.h>
#import "UIImage+Color.h"
#import "NSObject+Swizzling.h"

@interface HLogin2ViewController ()
@property (nonatomic, copy)NSString *APPUUID;

@end

@implementation HLogin2ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登录";
    self.APPUUID = [HAPPUUID getDeviceIDInKeychain];
    [self.view addSubview:[self LoginScorollView]];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];

}

-(void) DoLogin{
    
    [self hideKeyboard];
    
    NSString* username = self.LoginUserNameTextField.text;
    
    NSString* password = self.LoginUserPwdTextField.text;
    
    NSString *PassWord = [[super md5:self.LoginUserPwdTextField.text] lowercaseString];
    
    
    if([username isEqualToString:@""]){
        [self.LoginUserNameTextField becomeFirstResponder];
        [HCommon popupErrorMessage: @"工号不能为空!"];
        return;
    }
    
    if([username isEqualToString:@"wwwww"]){
        HLoginSettingViewController *hlsvc = [[HLoginSettingViewController alloc]init];
        [self.navigationController pushViewController:hlsvc animated:YES];
        return;
    }
    
    if( [username containsString:@"*"] || [username containsString:@"#"] ||  [username containsString:@"&"] ){
        [HCommon popupErrorMessage: @"工号格式错误!"];
        
        return;
    }
    
    [HCommon popupMessage:@"正在登录"];
    NSString *serviceUrl = AppServiceConfig.GetServiceUrl;
    NSString *url = [NSString stringWithFormat:@"%@/login?user_code=%@&user_password=%@&machine_code=%@",serviceUrl,username,PassWord,self.APPUUID];
    
    if (password.length == 0) {
        
        url = [NSString stringWithFormat:@"%@/login?user_code=%@&user_password=&machine_code=%@",serviceUrl,username,self.APPUUID];
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [HCommon dismissMessage];
        
        Boolean flag =  [[responseObject valueForKey:@"flag"] boolValue];
        NSString *msg = (NSString*)[responseObject objectForKey: @"msg" ];
        
        if(!flag){
            
            [HCommon popupErrorMessage:msg];
            
            return;
        }
        // 安装表结构
        InitDbTable* inittb = [[InitDbTable alloc]init];
        [inittb createDbTable];
    
        [[TMCache sharedCache]setObject:[responseObject objectForKey:@"data"] forKey:kLoginData];

        [[TMCache sharedCache]setObject:[responseObject objectForKey:@"menu"] forKey:@"menu"];
  
        [[TMCache sharedCache]setObject:[responseObject objectForKey:@"token"] forKey:@"deviceToken"];
        
        if ([[[responseObject objectForKey:@"menu"]valueForKey:@"NAME"]containsObject:@"科室排班"]) {
            NSInteger index = [[[responseObject objectForKey:@"menu"]valueForKey:@"NAME"] indexOfObject:@"科室排班"];
            NSString *string=  [[[responseObject objectForKey:@"menu"]objectAtIndex:index] objectForKey:@"PARAM"];
            
            NSString *stringUP = @"";
            
            if (![string isEqual:[NSNull null]]) {
                
                stringUP = [string uppercaseString];
            }else {
                stringUP = string;
            }
            NSDictionary *dic = [super getMenuParam:stringUP];
            
            [[TMCache sharedCache]setObject:[dic objectForKey:@"MENUID"]forKey:@"MENUID"];

        };

        AppDelegate *app = (AppDelegate *)[[UIApplication  sharedApplication] delegate];
        [app rootViewToTabBar];
      
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [HCommon dismissMessage];
        if (![error.userInfo isEqual:[NSNull null]]) {
            NSString *err = [NSString stringWithFormat:@"%ld:%@",(long)error.code,[error.userInfo objectForKey:@"NSLocalizedDescription"]];
            [self alert:err];
        }else {
            NSString *Error = [NSString stringWithFormat:@"%@",error];
            [self alert:Error];
        }
    }];
}



#pragma mark 登录相关的控件

-(UITextField*) LoginTextField{

    NSInteger inputWidth = ScreenWidth * 0.8 , inputHeight = 38;
    
    UITextField* LoginName = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, inputWidth, inputHeight)];
    LoginName.returnKeyType = UIReturnKeyNext;
    LoginName.keyboardType = UIKeyboardTypeDefault;
    LoginName.center = self.view.center;
    LoginName.delegate = self;
    LoginName.backgroundColor = RGB(0xE0, 0xFF, 0xFF);
    LoginName.layer.borderWidth = 1;
    LoginName.layer.borderColor = [RGB(218, 218, 218)CGColor];
    LoginName.layer.cornerRadius = 5;
    LoginName.layer.masksToBounds = YES;
 
    UIImageView *imagev = [[UIImageView alloc]initWithFrame:CGRectMake(10, 0, 20, 20)];
    imagev.image = [UIImage imageNamed:@"密码(1)"];
    LoginName.leftView = imagev;
    LoginName.leftViewMode = UITextFieldViewModeAlways;
      
    return LoginName;
}


-(UIScrollView*) LoginScorollView{
    
    NSInteger picWidth = 90, picHeight = 90;
    UIScrollView *mainview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, NavBarHeight, ScreenWidth, ScreenHeight)];
    
    UIImageView *hospitalLogo = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, picWidth, picHeight)];
    hospitalLogo.layer.cornerRadius = picWidth / 2;
    hospitalLogo.layer.masksToBounds = YES;
    [hospitalLogo setImage:[UIImage imageNamed:@"icon"]];
    hospitalLogo.center = self.view.center;
    hospitalLogo.top = 20;
    
    self.LoginUserNameTextField = [self LoginTextField];
    self.LoginUserNameTextField.top = hospitalLogo.bottom + 30;
    self.LoginUserNameTextField.tag = 1;
    self.LoginUserNameTextField.placeholder = @"工号";
    
    self.LoginUserPwdTextField = [self LoginTextField];
    self.LoginUserPwdTextField.top = self.LoginUserNameTextField.bottom + 30;
    self.LoginUserPwdTextField.returnKeyType = UIReturnKeyGo;
    self.LoginUserPwdTextField.secureTextEntry = YES;
    self.LoginUserPwdTextField.tag = 2;
    self.LoginUserPwdTextField.placeholder = @"密码";

    UIButton *LoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    LoginBtn.frame = CGRectMake(20, 0, ScreenWidth - 40, 40);
    LoginBtn.top = self.LoginUserPwdTextField.bottom + 20;
    LoginBtn.left = self.LoginUserPwdTextField.left;
    LoginBtn.width = self.LoginUserPwdTextField.width;
    LoginBtn.right =  self.LoginUserPwdTextField.right;
    
    LoginBtn.layer.masksToBounds = YES;
    LoginBtn.layer.cornerRadius = 7;
    LoginBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    LoginBtn.backgroundColor = RGB(13, 140, 236);
    [LoginBtn setTitle:@"登录" forState:UIControlStateNormal];
    
    LoginBtn.titleLabel.font= [UIFont systemFontOfSize:20];
    [LoginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [LoginBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [LoginBtn addTarget:self action:@selector(didLoginBtnClicked:) forControlEvents:UIControlEventTouchUpInside];

    
    UIButton *machineBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    machineBtn.frame = CGRectMake(0, 0, 100, 40);
    machineBtn.top = LoginBtn.bottom + 15;
    machineBtn.right =  self.LoginUserPwdTextField.right;
    
    [machineBtn setTitle:@"设备登记" forState:UIControlStateNormal];
    
    machineBtn.titleLabel.font= [UIFont systemFontOfSize:16];
    [machineBtn setTitleColor:RGB(13, 140, 236) forState:UIControlStateNormal];
    [machineBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [machineBtn addTarget:self action:@selector(watchMachine:) forControlEvents:UIControlEventTouchUpInside];
    


    mainview.delaysContentTouches = NO;
    [mainview addSubview:hospitalLogo];
    [mainview addSubview:self.LoginUserNameTextField];
    [mainview addSubview:self.LoginUserPwdTextField];
    [mainview addSubview:LoginBtn];
    [mainview addSubview:machineBtn];
    
    
    return mainview;
}

- (void)watchMachine:(UIButton *)sender
{
    
    [self alertMachine:self.APPUUID callbackYesFn:^{
        
        UIPasteboard *pab = [UIPasteboard generalPasteboard];
        
        [pab setString:self.APPUUID];
        
        if (pab == nil) {
            [HCommon popupErrorMessage:@"复制失败"];
            
        }else
        {
            [HCommon popupSuccessMessage:@"复制成功"];
        }
        
    } callbackNoFn:^{
        
    }];
}
- (void)didLoginBtnClicked:(UIButton *)sender{
    [self DoLogin];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark 文本框 委托 

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.tag == 1){
        if([textField.text isEqualToString:@"wwwww"]){
            [textField resignFirstResponder];
            HLoginSettingViewController *hlsvc = [[HLoginSettingViewController alloc]init];
            [self.navigationController pushViewController:hlsvc animated:YES];
        }else{
            [self.LoginUserPwdTextField becomeFirstResponder];
        }
    }else{
        [self DoLogin];
        [textField resignFirstResponder];
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    [textField resignFirstResponder];
}

-(void) hideKeyboard{
    [self.LoginUserNameTextField resignFirstResponder];
    [self.LoginUserPwdTextField resignFirstResponder];
}


@end
